package es.acm.calendario
{
	import avmplus.getQualifiedClassName;
	
	import es.acm.calendario.flex.DayCalendar;
	
	import flash.utils.describeType;
	import flash.utils.getDefinitionByName;
	
	import mx.controls.Alert;
	import mx.core.IFactory;
	
	public class DayCalendarFactory
	{
		private static var ResultClass:Class;
		
		public function DayCalendarFactory()
		{
		}
		
		public static function initResultClass():void {
			ResultClass = null;
		}
		
		private static function getClass(obj:Object):Class {
			return Class(getDefinitionByName(getQualifiedClassName(obj)));
		}
		
		private static function isIDayCalendar(obj:*):Boolean {
			var result:Boolean=true;
			
			var classDescription:XML = describeType(obj);
			if (classDescription.implementsInterface.(@type == getQualifiedClassName(IDayCalendar)).length() == 0) {
				result = false;
				trace ('Class "' + getQualifiedClassName(obj) + '" must implement IDayCalendar.\n\nDefault "IDayCalendar" used instead.', 'Error');
			}
			
			return result;
		}
		
		public static function getInstance(type:IFactory, clazz:Class=null):IDayCalendar {
			if (!ResultClass) {
				var obj:*;
				if (type) {
					if (type is IFactory) {
						obj = type.newInstance();
						if (isIDayCalendar(obj)) {
							ResultClass = getClass(obj);
						}
					}
				} else if (clazz) {
					obj = new clazz();
					if (isIDayCalendar(obj)) {
						ResultClass = getClass(obj);
					}
				}
				
				if (!ResultClass) {
					ResultClass = DayCalendar;
				}
			}
			
			return new ResultClass();
		}
	}
}